//===============================================================================
// Microsoft patterns & practices
// Web Client Software Factory
//===============================================================================
// Copyright � Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.ObjectBuilder;
using MVPComposibility.ContactManager.Views.ContactList;

namespace MVPComposibility.ContactManager.Views.ContactList
{
	public class ContactListPresenter : Presenter<IContactListView>
	{
		private IContactListModel _model;

		[CreateNew]
		public IContactListModel Model
		{
			get { return _model; }
			set
			{
				if (_model != null)
				{
					_model.ContentChanged -= Model_ContentChanged;
				}
				_model = value;
				if (_model != null)
				{
					_model.ContentChanged += Model_ContentChanged;
				}
			}
		}

		void Model_ContentChanged(object sender, EventArgs e)
		{
			View.SetContactList(_model.GetAllContacts());
		}

		public override void OnViewInitialized()
		{
			View.SetContactList(Model.GetAllContacts());
			View.SelectedContactIndex = -1;
		}

		public override void OnViewLoaded()
		{
			View.SelectedContactIndexChanged += OnViewSelectedContactIndexChanged;
			Model.RestoreSelectedContactFromPersistentState(View.SelectedContactIndex);
		}

		private void OnViewSelectedContactIndexChanged(object sender, EventArgs e)
		{
			Model.SelectedContactIndex = View.SelectedContactIndex;
		}
	}
}